package edu.school.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import edu.school.entity.Tiezi;
import edu.school.entity.TieziExample;
import edu.school.entity.User;
import edu.school.mapper.TieziMapper;
import edu.school.mapper.UserMapper;
import edu.school.service.TieziService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TieziServiceImpl implements TieziService {
    @Autowired
    TieziMapper mapper;
    @Autowired
    UserMapper userMapper;
    @Override
    public boolean save(Tiezi user) {
        return mapper.insertSelective(user)>0?true:false;
    }

    @Override
    public boolean update(Tiezi user) {
        return mapper.updateByPrimaryKeySelective(user)>0?true:false;
    }

    @Override
    public PageInfo<Tiezi> getPageList(Integer pageNum, Integer pageSize, Tiezi record) {
        TieziExample example = new TieziExample();
        example.setOrderByClause("create_time desc");
        TieziExample.Criteria criteria = example.createCriteria();
        if (null != record) {
            if (StringUtils.isNoneBlank(record.getTitle())) {//公告标题查询
                criteria.andTitleLike("%" + record.getTitle() + "%");
            }
            if (null!=record.getUser_id()){
                criteria.andUser_idEqualTo(record.getUser_id());
            }

        }
        PageHelper.startPage(pageNum, pageSize);//第1步
        List<Tiezi> list = mapper.selectByExample(example);//第2步
        for (Tiezi tiezi : list) {
            User user = userMapper.selectByPrimaryKey(tiezi.getUser_id());
            if (null!=user){
                tiezi.setUser(user);
            }
        }
        PageInfo<Tiezi> info = new PageInfo<>(list);
        info.setPageNum(info.getPageNum());
        info.setPages(info.getPages());
        return info;

    }

    @Override
    public Tiezi findById(Integer id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public boolean deleteTiezi(Integer id) {
        return mapper.deleteByPrimaryKey(id)>0?true:false;
    }

    @Override
    public int deleteMany(String[] ids) {
        return mapper.deleteMany(ids);
    }
}
